package com.uwo.house.controller;

import com.alibaba.fastjson.JSONObject;
import com.uwo.house.util.HttpUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by yanhao on 2017/6/16.
 */
@Controller
public class IndexController {

    @RequestMapping(value = {"", "/"})
    @ResponseBody
    public Object index(){
        return "OK";
    }

    @RequestMapping(value = "getOpenId", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getOpenId(HttpServletRequest request) {
        String code = request.getParameter("code");

        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=wx115677d9a2a5a079" +
                "&secret=008a081d7e2c098fd4540de89985f7c4" +
                "&code=" + code +
                "&grant_type=authorization_code";

        String result = HttpUtil.httpClientPost(tokenUrl);
        JSONObject resultJson = JSONObject.parseObject(result);
        String openId = resultJson.getString("openid");

        HttpSession session = request.getSession();
        session.setAttribute("openId", openId);
        return resultJson;
    }
}
